import os
import json
import tempfile

class Config:
    def __init__(self):
        self.base_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        self.settings_file = os.path.join(self.base_dir, "settings.json")
        self.tasks_file = os.path.join(self.base_dir, "tasks.json")
        self.douyin_cookies_file = os.path.join(self.base_dir, "douyin_cookies.txt")
        
        # 默认下载目录
        self.default_download_dir = os.path.join(os.path.expanduser("~"), "Downloads", "VideoDownloader")
        
        # 下载器配置
        self.max_concurrent_downloads = 3
        self.download_retries = 3
        self.download_timeout = 30
        
        # 加载设置
        self.load_settings()
        
        # 初始化 cookies 文件
        self.init_cookies_file()
    
    def load_settings(self):
        """加载设置"""
        try:
            if os.path.exists(self.settings_file):
                with open(self.settings_file, "r", encoding="utf-8") as f:
                    settings = json.loads(f.read())
                    download_dir = settings.get("download_dir", self.default_download_dir)
            else:
                download_dir = self.default_download_dir
            
            # 确保下载目录存在并具有正确的权限
            try:
                os.makedirs(download_dir, exist_ok=True)
                # 测试目录是否可写
                test_file = os.path.join(download_dir, ".test")
                with open(test_file, "w") as f:
                    f.write("test")
                os.remove(test_file)
                self.download_dir = download_dir
            except (OSError, IOError) as e:
                print(f"下载目录权限错误: {str(e)}")
                # 如果默认目录不可用，尝试使用临时目录
                self.download_dir = os.path.join(tempfile.gettempdir(), "VideoDownloader")
                os.makedirs(self.download_dir, exist_ok=True)
            
            self.save_settings()
        except Exception as e:
            print(f"加载设置失败: {str(e)}")
            # 使用临时目录作为后备方案
            self.download_dir = os.path.join(tempfile.gettempdir(), "VideoDownloader")
            os.makedirs(self.download_dir, exist_ok=True)
            self.save_settings()
    
    def save_settings(self):
        """保存设置"""
        try:
            settings = {
                "download_dir": self.download_dir
            }
            with open(self.settings_file, "w", encoding="utf-8") as f:
                json.dump(settings, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存设置失败: {str(e)}")
    
    def init_cookies_file(self):
        """初始化 cookies 文件"""
        if not os.path.exists(self.douyin_cookies_file):
            with open(self.douyin_cookies_file, "w", encoding="utf-8") as f:
                f.write("# 抖音 cookies 文件，请将抖音网页版的 cookies 粘贴到这里\n")
                f.write("# 格式: domain_name\tFALSE\tpath\tFALSE\texpiry_epoch\tname\tvalue\n")
    
    def get_headers(self):
        """获取通用请求头"""
        return {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        } 